<template>
  <div style="width: 100%">
    <div style="padding: 20px" class="step_line">
      <el-form
        label-position="top"
        :model="ruleForm"
        class="inputForm"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable"
      >
        <div class="info_tab">揽收信息</div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="揽收单号" prop="number">
              <el-input id="collect_batch" v-model="ruleForm.number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="揽收类型" prop="type">
              <el-select
                id="collect_type_down"
                :disabled="typeDisable"
                v-model="ruleForm.type"
                placeholder="请选择"
                @change="collectionNetwork()"
              >
                <el-option
                  id="collect_type"
                  v-for="item in types"
                  :label="item.value"
                  :value="item.index"
                  :key="item.index"
                  >{{ item.value }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="ruleForm.type == '1'">
            <el-form-item
              label="揽收公司"
              prop="company_id"
              :class="{
                'select-add': isHavePermission('company_carrier_create'),
              }"
            >
              <el-select
                id="collect_company_down"
                v-model="ruleForm.company_id"
                class="select-left"
                @change="handleChangeCompany"
                filterable
                allow-create
                placeholder="请选择"
              >
                <el-option
                  id="collect_company"
                  v-for="item in companyData"
                  :label="item.name"
                  :value="item.id + ''"
                  :key="item.id"
                  >{{ item.name }}</el-option
                >
              </el-select>
              <el-button
                v-permission="'company_carrier_create'"
                @click="handleAddMaterial('carrier')"
                class="add-right"
                >+</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="ruleForm.type == '0'">
            <el-form-item label="揽收网点" prop="from_network_id">
              <el-input
                v-if="mode === 'detail' || mode === 'singleDetail'"
                id="from_network_address"
                disabled
                v-model="ruleForm.from_network_name"
              ></el-input>

              <el-cascader
                v-else
                ref="cascader"
                style="width: 100%"
                :options="branchData"
                :show-all-levels="false"
                @change="handleChangeNetwork"
                v-model="ruleForm.from_network_id"
                :props="{
                  emitPath: false,
                  checkStrictly: true,
                  label: 'branch_name',
                  value: 'id',
                  children: 'next_level_data',
                }"
                clearable
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="揽收始发地址" prop="from_network_address">
              <el-input
                id="from_network_address"
                v-model="ruleForm.from_network_address"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="揽收目的地址" prop="take_address">
              <el-input
                id="to_network_address"
                v-model="ruleForm.take_address"
                @change="take_address_change()"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计揽收完成时间" prop="scheduled_time">
              <el-date-picker
                id="scheduled_time_select"
                v-model="ruleForm.scheduled_time"
                type="datetime"
                placeholder="选择日期时间"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="揽收司机"
              :class="{
                'select-add': isHavePermission('company_driver_create'),
              }"
              prop="motorist_id"
              :rules="ruleForm.type == '0' ? rules.motorist_id : {}"
            >
              <el-input
                v-if="mode === 'detail' || mode === 'singleDetail'"
                disabled
                v-model="ruleForm.driver_name"
              ></el-input>
              <template v-else>
                <el-select
                  id="collect_driver_down"
                  v-model="ruleForm.motorist_id"
                  class="select-left"
                  filterable
                  placeholder="请选择"
                  @change="handleChangeDriver"
                >
                  <el-option
                    id="collect_driver"
                    v-for="item in driverData"
                    :label="item.name"
                    :value="item.id + ''"
                    :key="item.id"
                    >{{ item.name }}</el-option
                  >
                </el-select>
                <el-button
                  v-permission="'company_driver_create'"
                  @click="handleAddMaterial('driver')"
                  class="add-right"
                >
                  +
                </el-button>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="揽收司机电话"
              prop="take_mobile"
              :rules="ruleForm.type == '0' ? rules.take_mobile : {}"
            >
              <el-input v-model="ruleForm.take_mobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="揽收车牌号"
              prop="car_no_id"
              :class="{
                'select-add': isHavePermission('company_vehicle_create'),
              }"
              :rules="{
                required: [2, 4].indexOf(this.businessType) > -1,
                message: '请选择揽收车牌号',
                trigger: 'change',
              }"
            >
              <el-select
                id="collect_car_no_down"
                v-model="ruleForm.car_no_id"
                filterable
                class="select-left"
                @change="selectCarNumber"
                placeholder="请选择"
              >
                <el-option
                  id="collect_car_no"
                  v-for="item in carNumberData"
                  :label="item.license_plate"
                  :value="item.id + ''"
                  :key="item.id"
                  >{{ item.license_plate }}</el-option
                >
              </el-select>
              <el-button
                v-permission="'company_vehicle_create'"
                @click="handleAddMaterial('car')"
                class="add-right"
                >+</el-button
              >
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="承运单号"
              prop="carrier_number"
              v-if="ruleForm.type == '1'"
            >
              <el-input
                id="carrier_number"
                v-model="ruleForm.carrier_number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="create_time">
              <el-date-picker
                v-model="ruleForm.create_time"
                clearable
                type="datetime"
                placeholder="选择日期时间"
                value-format="timestamp"
                :disabled="mode === 'edit' || mode === 'singleEdit'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
            <el-form-item label="操作时间" prop="update_time">
              <el-date-picker
                :value="ruleForm.update_time * 1000"
                type="datetime"
                placeholder="选择日期时间"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col
            :span="6"
            v-if="
              (mode === 'detail' || mode === 'singleDetail') &&
              ruleForm.status === '1'
            "
          >
            <el-form-item label="实际揽收完成时间" prop="collect_time">
              <el-date-picker
                :value="ruleForm.collect_time * 1000"
                type="datetime"
                placeholder="选择日期时间"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="info_tab">负责人信息</div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="运营" prop="operation_id">
              <el-select
                v-model="ruleForm.operation_name"
                filterable
                remote
                :remote-method="(val) => remoteMethod(val, 'operation')"
                placeholder="请选择"
                @change="(val) => handleChangeCharge(val, 'operation')"
              >
                <el-option
                  v-for="item in motionData"
                  :label="item.name"
                  :value="item.id + ''"
                  :key="item.id"
                  >{{ item.name }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运营电话" prop="operation_phone">
              <el-input v-model="ruleForm.operation_phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作" prop="action_id">
              <el-select
                v-model="ruleForm.action_name"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择"
                @change="(val) => handleChangeCharge(val, 'action')"
              >
                <el-option
                  v-for="item in chargeData"
                  :label="item.name"
                  :value="item.id + ''"
                  :key="item.id"
                  >{{ item.name }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作电话" prop="action_phone">
              <el-input v-model="ruleForm.action_phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调度" prop="dispatch_id">
              <el-select
                v-model="ruleForm.dispatch_name"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择"
                @change="(val) => handleChangeCharge(val, 'dispatch')"
              >
                <el-option
                  v-for="item in chargeData"
                  :label="item.name"
                  :value="item.id + ''"
                  :key="item.id"
                  >{{ item.name }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调度电话" prop="dispatch_phone">
              <el-input v-model="ruleForm.dispatch_phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="info_tab">
          <div>费用信息</div>
          <!-- <div class="info_tab_list">
            <div>计费规则 <span style="margin-right:2px;">:</span></div>
            <div style="margin-left:5px">
              <el-select v-model="rule_cost_info_id" clearable placeholder="请选择" @change="rulechange(rule_cost_info_id)"
                style="width:120px">
                <el-option v-for="item in rule_cost_info" :key="item.rule_id" :label="item.rule_name"
                  :value="item.rule_id">
                </el-option>
              </el-select>
            </div>
          </div> -->
        </div>
        <div
          style="margin-bottom: 10px"
          v-if="!disable && ruleForm.is_add_waybill !== '1'"
        >
          <el-button type="primary" plain size="mini" @click="handleAddWaybill"
            >新增运单</el-button
          >
          <el-button type="primary" plain size="mini" @click="handleDelWaybill"
            >删除运单</el-button
          >
        </div>
        <el-table
          :data="ruleForm['waybill_data_list']"
          default-expand-all
          @selection-change="handleSelectionChange"
          class="safari_table"
          style="width: 100%; margin-bottom: 20px"
          :key="is_incubator + ''"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table
                :data="props.row.goods"
                style="width: 100%"
                v-if="props.row.goods"
                :show-header="false"
              >
                <el-table-column label="操作" prop="" width="98">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      style="padding: 4px"
                      circle
                      @click="handleAddGood(props.row.goods)"
                    >
                      <i class="el-icon-plus"></i>
                    </el-button>
                    <el-button
                      size="mini"
                      style="padding: 4px"
                      circle
                      @click="handleDelGood(props.row.goods, scope.$index)"
                      ><i class="el-icon-minus"></i
                    ></el-button>
                  </template>
                </el-table-column>
                <el-table-column label="货物名称" prop="name" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row['name']"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="件数" prop="number" width="100">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row['number']"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      @input="handleInputTotal"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="重量" prop="weight" width="100">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row['weight']"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      @input="handleInputTotal"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="体积" prop="volume" width="100">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row['volume']"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      @input="handleInputTotal"
                    ></el-input>
                  </template>
                </el-table-column>
                <template v-if="is_incubator">
                  <el-table-column label="温层" prop="thermosphere" width="120">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row['thermosphere']"
                        placeholder="请选择"
                        clearable
                        filterable
                      >
                        <el-option
                          v-for="item in thermosphereData"
                          :label="item.item_name"
                          :value="item.item_code"
                          :key="item.item_code"
                          >{{ item.item_name }}</el-option
                        >
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="包装型号"
                    width="120"
                    prop="package_type"
                  >
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row['package_type']"
                        placeholder="请选择"
                        clearable
                        filterable
                      >
                        <el-option
                          v-for="item in packageData"
                          :label="item.item_name"
                          :value="item.item_code"
                          :key="item.item_code"
                          >{{ item.item_name }}</el-option
                        >
                      </el-select>
                    </template>
                  </el-table-column>
                </template>
                <template v-else>
                  <el-table-column label="货物包装" width="100">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.packing"
                        clearable
                        placeholder=""
                      >
                        <el-option label="纸箱" value="0"> </el-option>
                        <el-option label="木箱" value="1"> </el-option>
                        <el-option label="纤袋" value="2"> </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                </template>

                <el-table-column label="包装数量" width="100">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row['package_quantity']"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      @input="handleInputTotal"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="温度计" width="100">
                  <template slot-scope="scope">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="
                        getTheroName(scope.row.waybill_devices) || '温度计绑定'
                      "
                      placement="top"
                    >
                      <div @click="is_incubator && handleClickBind(scope.row)">
                        <el-input
                          id="binding_thermometer"
                          :disabled="!is_incubator"
                          :value="getTheroName(scope.row.waybill_devices)"
                        ></el-input>
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label=""> </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="运单号" width="120">
            <template slot-scope="scope">
              {{ scope.row["waybill_no"] }}
            </template>
          </el-table-column>
          <el-table-column label="件数" width="100">
            <template slot-scope="scope">
              <el-input disabled v-model="scope.row['number']"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="重量（kg）" width="100">
            <template slot-scope="scope">
              <el-input disabled v-model="scope.row['weight']"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="体积（m³）" width="100">
            <template slot-scope="scope">
              <el-input disabled v-model="scope.row['volume']"></el-input>
            </template>
          </el-table-column>
          <!-- 保温箱 -->
          <template v-if="is_incubator">
            <el-table-column label="温层" width="120">
              <el-input disabled></el-input>
            </el-table-column>
            <el-table-column label="包装型号" width="120">
              <el-input disabled></el-input>
            </el-table-column>
          </template>
          <!-- 非保温箱 -->
          <el-table-column label="货物包装" width="100" v-else>
            <el-input disabled></el-input>
          </el-table-column>
          <el-table-column label="包装数量" width="100">
            <template slot-scope="scope">
              <el-input
                disabled
                v-model="scope.row['package_quantity']"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="温度计" width="100">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  getTheroName(scope.row.waybill_devices) || '温度计绑定'
                "
                placement="top"
              >
                <div @click="!is_incubator && handleClickBind(scope.row)">
                  <el-input
                    :disabled="is_incubator"
                    :value="
                      !is_incubator
                        ? getTheroName(scope.row.waybill_devices)
                        : ''
                    "
                  ></el-input>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="揽收提货费"
            width="100"
            prop="collect_money"
            property="collect_money"
          >
            <template #header>
              <div v-if="rules.collect_money[0].required">
                <span style="color: red">*</span> <span>揽收提货费</span>
              </div>
              <div v-else>
                <span>揽收提货费</span>
              </div>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="classbottom"
                style="margin-bottom: 1px"
                :prop="'waybill_data_list.' + scope.$index + '.collect_money'"
                :rules="rules.collect_money"
              >
                <el-input
                  id="collect_money"
                  v-model="scope.row['collect_money']"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="揽收包装费" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['package_money']"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="揽收装卸费" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['handling_money']"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="揽收发货费" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['delivery_money']"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="机场提货费" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['airport_pick_money']"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="干冰费" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['dry_ice_money']"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label=""> </el-table-column>
          <!--
          <el-table-column label="操作" :width="is_incubator ? 1 : 120">
            <template slot-scope="scope" v-if="!is_incubator">
              <el-button size="small" type="primary" @click="handleClickBind(scope.row)">
                温度计绑定
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- <el-dialog title="绑定保温箱和温度计" :visible.sync="dialogVisible" v-if="dialogVisible" :key="Math.random()"
          width="600px">
          <PackingBind :good="currentGood" :acceptChange="true" @ok="handleClickOK" @close="dialogVisible = false">
          </PackingBind>
        </el-dialog> -->
        <div
          style="margin-top: 20px; text-align: right; padding-bottom: 20px"
          v-if="!disable"
        >
          <el-button id="create_cancel" @click="handleClickClose"
            >取消</el-button
          >
          <el-button
            id="create_ok"
            type="primary"
            data-tracker="P4-1"
            v-preventReClick
            @click="handleClickSubmit()"
            :loading="submitLoading"
            >{{ mode === "add" ? "开始揽收" : "修改" }}</el-button
          >
        </div>
      </el-form>
      <OperationWaybill
        step="1"
        :key="Math.random()"
        :waybill_product_type="waybillInfo.waybill_product_type"
        @close="handleOperationClose"
        @finish="handleOperationWaybillOk"
        v-if="waybillDialogShow"
        :visible="waybillDialogShow"
        :restParams="{
          from_network_id_list: [this.waybillInfo.from_network_id * 1],
        }"
      >
      </OperationWaybill>
      <MaterialAdd
        :type="materialType"
        @ok="handleMaterialAddOk"
        @close="handleCloseMaterialDialog"
        :dialogVisible="materialDialogVisible"
        :diaremark="1"
      >
      </MaterialAdd>
    </div>
    <div>
      <notify
        v-if="notifyType"
        :noTifyData="noTifyData"
        :key="noTifyData.node_id"
      ></notify>
    </div>
    <CostControl :showDialog="costDialogShow" :overWarning="overWarning" :tableData="cost_overruns_info" @ok="handleCostOk" @close="costDialogShow=false"></CostControl>
  </div>
</template>
<script>
import {
  deliveryAddFn,
  deliveryEditFn,
  carrierBox,
  driverBox,
  vehicleBox,
  deliveryDetailFn,
  WaybillDeliveryOptionFn,
  collectEditOne,
  getChargeDataBox,
  waybillExpectTime,
  searchChargeData,
  accountingrules, //计费规则接口
  recognitionListcity, //通过详细地址获取省市区的id
  DefaultPersonList,
  FeeEntryControl,
} from "@/api/waybill";
import { detailsDriver } from "@/api/information";
import { dictionanryList } from "@/page/material/common/common";
import { timestamp10, parseFen, parseYuan, commonAdd } from "@/utils/mUtils";
import { organizationDetail, organizationBox } from "@/api/organization";
import OperationWaybill from "../operationWaybill.vue";
import MaterialAdd from "../materialAdd.vue";
import { MATERIAL } from "@/page/waybill/constants";
import { isHavePermission } from "@/utils/mUtils";
import notify from "@/components/notify/notify.vue"; // 时间转化
import CostControl from "../costControl.vue";
export default {
  name: "singleDelivery",
  data() {
    return {
      submitLoading: false,
      ruleForm: {
        number: "", // 揽收单号
        type: "0", //揽收类型
        company_id: "", // 揽收公司id
        company_name: "", // 揽收公司name
        from_network_id: "", // 揽收网点
        from_network_name: "",
        from_network_address: "", //揽收始发地址
        take_address: "", // 揽收目的地址
        scheduled_time: "", // 预计揽收完成时间
        motorist_id: "", // 揽收司机
        driver_name: "",
        take_mobile: "", // 揽收司机电话
        carrier_number: "", //承运单号
        operation_id: "", // 运营
        operation_name: "",
        operation_phone: "",
        action_id: "", // 操作
        action_name: "",
        action_phone: "",
        dispatch_id: "", // 调度
        dispatch_name: "",
        dispatch_phone: "",
        waybill_data_list: [],
        create_time: "", //创建时间
      },
      rules: {
        company_id: [
          { required: true, message: "请选择揽收公司", trigger: "change" },
        ],
        motorist_id: [
          { required: true, message: "请选择揽收司机", trigger: "change" },
        ],
        take_mobile: [
          { required: true, message: "请填写揽收司机电话", trigger: "blur" },
        ],
        take_address: [
          { required: true, message: "请填写揽收目的地址", trigger: "blur" },
        ],
        car_no_id: [
          { required: true, message: "请填写揽收车牌号", trigger: "blur" },
        ],
        scheduled_time: [
          {
            required: true,
            message: "请填写预计揽收完成时间",
            trigger: "blur",
          },
        ],
        cost_way: [
          { required: true, message: "请选择费用分摊方式", trigger: "change" },
        ],
        temp_status_way: [
          { required: true, message: "请选择温度状态", trigger: "change" },
        ],
        collect_money: [
          { required: true, message: "请填写揽收提货费", trigger: "blur" },
        ],
        carrier_number: [
          { required: true, message: "请填写承运单号", trigger: "blur" },
        ],
        from_network_address: [
          { required: true, message: "请输入揽收始发地址", trigger: "blur" },
        ],
        from_network_id: [
          { required: true, message: "请输入揽收网点", trigger: "blur" },
        ],
        type: [{ required: true, message: "请输入揽收类型", trigger: "blur" }],
      },
      companyData: [],
      driverData: [],
      carNumberData: [],
      paymentData: [],
      thermosphereData: [],
      chargeData: [],
      motionData: [],
      packageData: [],
      organizaList: {}, //组织详情
      endareaList: {}, //发货地址详细地址
      rule_cost_info: [], //计费规则
      rule_cost_info_id: "",
      branchData: [],
      waybillDialogShow: false,
      checkedRows: [],
      types: [
        {
          index: "0",
          value: "自营",
        },
        {
          index: "1",
          value: "委外",
        },
      ],
      materialType: "",
      materialDialogVisible: false,
      MATERIAL: MATERIAL,
      typeDisable: false,
      notifyType: false,
      noTifyData: {
        customer_id: "",
        product_type_id: "",
        node_id: "",
      },
      cost_overruns_info:[
      ],//成本超出信息
      overWarning:"",
      costDialogShow:false,
    };
  },
  computed: {
    disable: function () {
      return this.mode === "detail" || this.mode === "singleDetail";
    },
    // 承运商和组织的符合，用于监听这两个字段是否发生变化
    driverEngine() {
      return Number(this.ruleForm.company_id) || this.ruleForm.from_network_id;
    },
  },
  components: { OperationWaybill, MaterialAdd, notify, CostControl},
  props: ["id", "mode", "ids", "waybillInfo", "is_incubator", "businessType"],
  inject: ["bindTemp"],
  watch: {
    id: {
      handler: function (val) {
        val && this.getDetail();
      },
      immediate: true,
    },
    mode: {
      handler: function () {
        this.handleChangeMode();
      },
      immediate: true,
    },
    driverEngine(val) {
      // console.log(
      //   Number(this.ruleForm.company_id),
      //   this.ruleForm.from_network_id
      // );
      if (val) {
        this.getDriverBox();
      } else {
        this.driverData = [];
        this.checkDriverId();
      }
    },
  },
  mounted() {
    carrierBox().then((res) => {
      this.companyData = res.data;
    });
    // driverBox().then((res) => {
    //   this.driverData = res.data;
    // });
    this.NotificationObj();
    vehicleBox().then((res) => {
      this.carNumberData = res.data;
    });
    dictionanryList(["thermosphere", "divide_way", "Package_model"]).then(
      (res) => {
        this.thermosphereData = res.data.list["thermosphere"];
        this.paymentData = res.data.list["divide_way"];
        this.packageData = res.data.list["Package_model"];
      }
    );
    organizationBox({ not_show_first_branch: 1 }).then((res) => {
      this.branchData = res.data;
      if (this.mode === "add") {
        this.collectionNetwork();
      }
    });
    FeeEntryControl({}).then((res) => {
      const data = res.data || {};
      this.rules.collect_money[0].required =
        data.switch_status == "0" ? true : false;
    });
  },
  methods: {
    isHavePermission(val) {
      return isHavePermission(val);
    },
    handleAddGood(goods) {
      goods.push({});
    },
    handleDelGood(goods, index) {
      if (goods.length === 1) {
        this.$message({
          message: "最后一条数据，不允许删除",
          type: "warning",
        });
        return;
      }
      goods.splice(index, 1);
      this.handleInputTotal();
    },
    getTheroName(devices) {
      const _devices = devices || [];
      return _devices.map((item) => item.thermometer_no).join(",");
    },
    handleInputTotal() {
      this.ruleForm.waybill_data_list.forEach((waybill) => {
        waybill.number =
          waybill.goods &&
          waybill.goods.reduce((prev, next) => {
            return commonAdd(prev, next.number * 1);
          }, 0) + "";
        waybill.weight =
          waybill.goods &&
          waybill.goods.reduce((prev, next) => {
            return commonAdd(prev, next.weight * 1);
          }, 0) + "";
        waybill.volume =
          waybill.goods &&
          waybill.goods.reduce((prev, next) => {
            return commonAdd(prev, next.volume * 1);
          }, 0) + "";
        waybill.package_quantity =
          waybill.goods &&
          waybill.goods.reduce((prev, next) => {
            return commonAdd(prev, next.package_quantity * 1);
          }, 0) + "";
      });
    },
    handleAddMaterial(materialType) {
      this.materialType = materialType;
      this.materialDialogVisible = true;
    },
    handleCloseMaterialDialog() {
      this.materialDialogVisible = false;
    },
    handleMaterialAddOk() {
      const { MATERIAL } = this;
      if (this.materialType === MATERIAL.CAR) {
        this.getCarBox();
      } else if (this.materialType === MATERIAL.DRIVER) {
        this.getDriverBox();
      } else if (this.materialType === MATERIAL.CARRIER) {
        this.getCarrierBox();
      }
    },
    getCarBox() {
      vehicleBox().then((res) => {
        this.carNumberData = res.data;
      });
    },
    getDriverBox() {
      let carrier_id;
      if (this.ruleForm.type === "0") {
        carrier_id = this.ruleForm.from_network_id + "";
      } else {
        carrier_id = this.ruleForm.company_id;
      }
      driverBox({
        driver_type: this.ruleForm.type,
        carrier_id,
      }).then((res) => {
        this.driverData = res.data;
        this.checkDriverId();
      });
    },
    // 校验司机id是否在data中，没有清空
    checkDriverId() {
      const isInData =
        this.driverData.findIndex(
          (item) => item.id === this.ruleForm.motorist_id * 1
        ) > -1;
      if (!isInData && !this.disable) {
        this.ruleForm.motorist_id = ""; // 揽收司机
        this.ruleForm.driver_name = "";
      }
    },
    getCarrierBox() {
      carrierBox().then((res) => {
        this.companyData = res.data;
      });
    },
    setDefaultPerson() {
      DefaultPersonList({ waybill_id: this.waybillInfo.id * 1 }).then((res) => {
        if (res.code === 10000) {
          const { action_info, dispatch_info, operation_info } =
            res.data.data || {};
          if (operation_info) {
            this.ruleForm.operation_id = operation_info.id + "";
            this.ruleForm.operation_name = operation_info.name;
            this.ruleForm.operation_phone = operation_info.mobile;
          }
          if (action_info) {
            this.ruleForm.action_id = action_info.id + "";
            this.ruleForm.action_name = action_info.name;
            this.ruleForm.action_phone = action_info.mobile;
          }
          if (dispatch_info) {
            this.ruleForm.dispatch_id = dispatch_info.id + "";
            this.ruleForm.dispatch_name = dispatch_info.name;
            this.ruleForm.dispatch_phone = dispatch_info.mobile;
          }
        }
      });
    },
    handleChangeMode() {
      if (
        this.mode === "edit" ||
        this.mode === "detail" ||
        this.mode === "singleDetail" ||
        this.mode === "singleEdit"
      ) {
        this.getDetail();
      } else if (this.mode === "add") {
        this.initWaybillData();
        // 默认负责人
        this.setDefaultPerson();
        // 默认承运商
        this.setDefaultCompany();
        // 预计揽收完成时间默认为运单的提货时间
        const { start_time: collect_start_time } =
          this.waybillInfo.collect_time;
        if (collect_start_time !== "" && collect_start_time !== "0") {
          this.ruleForm.scheduled_time = collect_start_time * 1000;
        }
        this.ruleForm.create_time = Date.now();
      }
    },
    getDetail() {
      if (!this.id) return;
      deliveryDetailFn({ id: this.id }).then((res) => {
        const data = res.data;
        if(!data) return;
        data.number = data.batch;
        data.scheduled_time = data.scheduled_time * 1000;
        data.create_time = data.create_time * 1000;
        /**
         * 暂时测试
         */
        data.from_network_address = data.from_network_address || "";
        data.from_network_id = data.from_network_id && data.from_network_id * 1;
        // data.company_id = data.company_id ==='0'? '': data.company_id;
        data.waybill_data_list &&
          data.waybill_data_list.forEach((item) => {
            item.goods = item.goods || [];
          });
        this.ruleForm = data;
        // console.log("111111");
        // console.log(this.ruleForm, "this.ruleForm");
        // console.log(this.driverData, "this.driverData");
        // console.log(data, "datatat");
      });
    },

    handleClickClose() {
      this.$emit("update");
    },

    remoteMethod(nickname, key, params = {}) {
      searchChargeData({ nickname, ...params }).then((res) => {
        if (key === "operation") {
          this.motionData = res.data;
        } else {
          this.chargeData = res.data;
        }
      });
    },
    handleChangeCharge(val, key) {
      const chargeData =
        key === "operation" ? this.motionData : this.chargeData;
      const charge = chargeData.find((item) => item.id === Number(val));
      if (charge) {
        this.ruleForm[key + "_phone"] = charge.mobile;
        this.ruleForm[key + "_name"] = charge.name;
        this.ruleForm[key + "_id"] = charge.id + "";
      }
    },
    async handleClickBind(rowItem) {
      // 详情不能点击
      if (this.mode === "detail" || this.mode === "singleDetail") {
        return;
      }
      const waybillDevices = rowItem.waybill_devices || [];
      let startTime = "";
      startTime = (waybillDevices[0] || {}).start_time;
      const { start_time, checkedTemperatures } = await this.bindTemp(
        startTime,
        rowItem.waybill_devices
      );
      this.$set(rowItem, "start_time", start_time);
      this.$set(rowItem, "waybill_devices", checkedTemperatures);
    },
    handleNext() {
      const { step } = this.$route.query;
      this.$router.push({
        query: { ...this.$route.query, step: Number(step) + 1 },
      });
    },
    handleChangeCompany(val) {
      const item = this.companyData.find((item) => item.id === Number(val));
      if (item) {
        this.ruleForm["company_name"] = item.name;
      } else {
        this.ruleForm["company_name"] = val;
      }
    },
    handleChangeDriver(val) {
      const driver = this.driverData.find((item) => item.id === Number(val));
      if (driver) {
        const { id, name, mobile } = driver;
        this.ruleForm.driver_name = name;
        this.ruleForm.take_mobile = mobile;
      } else {
        this.ruleForm.driver_name = val;
      }
    },
    handleCostOk(cost_overruns_info){
      this.ruleForm.waybill_cost_overruns_info=cost_overruns_info;
      this.handleClickSubmit()
    },
    judgeOver(res){
      if(res.data.warning){
        this.costDialogShow=true;
        this.overWarning=res.data.warning;
        this.cost_overruns_info=res.data.cost_overruns_info||[];
        this.submitLoading = false;
        return true;
      }
      return false
    },
    handleClickSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        this.submitLoading = true;
        const _ruleForm = {
          ...this.ruleForm,
          scheduled_time: timestamp10(this.ruleForm.scheduled_time),
          create_time: timestamp10(this.ruleForm.create_time),
          from_network_id: this.ruleForm.from_network_id
            ? this.ruleForm.from_network_id + ""
            : "",
          waybill_data_list: JSON.parse(
            JSON.stringify(this.ruleForm.waybill_data_list)
          ),
        };

        if (this.is_incubator) {
          for (let i = 0; i < _ruleForm.waybill_data_list.length; i++) {
            let waybill_devices = [];
            let goods = _ruleForm.waybill_data_list[i].goods || [];
            _ruleForm.waybill_data_list[i].goods.forEach((good, index) => {
              good.sequence = index + "";
              good.waybill_devices &&
                good.waybill_devices.forEach((item) => {
                  if (
                    item.incubator_type ||
                    item.incubator_cnt ||
                    item.thermometer_id
                  )
                    waybill_devices.push({
                      ...item,
                      goods_id: good.id,
                      sequence: good.sequence,
                      start_time: item.start_time,
                    });
                });
            });
            _ruleForm.waybill_data_list[i].waybill_devices = waybill_devices;
          }
        }
        // console.log(_ruleForm);
        if (this.mode === "add") {
          deliveryAddFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;

              this.$message({
                message: "新建成功",
                type: "success",
              });
              this.$emit("update");
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        } else {
          _ruleForm.id = Number(this.id);
          const editFn =
            this.mode === "singleEdit" ? collectEditOne : deliveryEditFn;
          deliveryEditFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;

              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$emit("update", false);
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              // console.log("编辑失败");
              this.submitLoading = false;
            }
          });
        }
      });
    },
    handleChangeNetwork(val, a) {
      const checkedNodes =
        (this.$refs["cascader"].getCheckedNodes() || [])[0] || {};
      const checkedData = checkedNodes.data;
      if (checkedData) {
        this.ruleForm.from_network_name = checkedData.branch_name;
        this.ruleForm.from_network_address = checkedData.address;
      }
    },
    getCheckedNodes(val) {
      // console.log(val, "getCheckedNodes");
    },

    handleAddWaybill() {
      this.waybillDialogShow = true;
    },
    handleDelWaybill() {
      if (this.checkedRows.length === 0) {
        this.$message({
          message: "请选中后进行删除哦",
          type: "warning",
        });
        return;
      }
      if (this.ruleForm.waybill_data_list.length === this.checkedRows.length) {
        this.$message({
          message: "揽收单下至少包含一个运单",
          type: "warning",
        });
        return;
      }
      this.ruleForm.waybill_data_list = this.ruleForm.waybill_data_list.filter(
        (item) => !this.checkedRows.includes(item.waybill_id)
      );
    },
    handleSelectionChange(checked) {
      this.checkedRows = checked.map((item) => item.waybill_id);
    },
    handleOperationWaybillOk(checkedWaybillIds) {
      const nowIds = this.ruleForm.waybill_data_list.map(
        (item) => item.waybill_id + ""
      );
      checkedWaybillIds = checkedWaybillIds.filter(
        (item) => !nowIds.includes(item + "")
      );
      this.getWaybillDataByIds(checkedWaybillIds);
    },
    handleOperationClose() {
      this.waybillDialogShow = false;
    },
    getWaybillDataByIds(ids) {
      const _ids = ids.map(Number);
      WaybillDeliveryOptionFn({ waybill_id_list: _ids }).then((res) => {
        if (res.data) {
          // this.ruleForm["waybill_data_list"] = res.data;
          this.ruleForm["waybill_data_list"] = (
            this.ruleForm["waybill_data_list"] || []
          ).concat(res.data);
          // 获取提货件数提货重量提货体积
          // this.invoking();
        } else {
          // this.$alert("以下运单无法新增提货，请检查后重新选择!", "操作提醒", {
          //   confirmButtonText: "确定",
          //   callback: (action) => {
          //     if (this.type === "layer") {
          //       this.$emit("close");
          //     } else {
          //       this.$router.push("/waybill/waybillPage");
          //     }
          //   },
          // });
        }
      });
    },
    initWaybillData() {
      this.getWaybillDataByIds(this.ids);
      this.$nextTick(() => {
        const { address } = (this.waybillInfo || {}).sender || {};
        this.ruleForm.take_address = address;
      });
    },
    collectionNetwork() {
      if (this.ruleForm.type == "0") {
        this.ruleForm.from_network_id = this.waybillInfo.from_network_id * 1;
        this.ruleForm.from_network_name = this.waybillInfo.from_network_name;
        this.$nextTick(() => {
          this.handleChangeNetwork();
        });
        this.ruleForm.company_id = "";
        this.ruleForm.company_name = "";
      } else if (this.ruleForm.type == "1") {
        this.ruleForm.from_network_id = "";
        this.ruleForm.from_network_name = "";
        this.ruleForm.from_network_address = "";
        this.ruleForm.company_id =
          this.ruleForm.company_id === "0" ? "" : this.ruleForm.company_id;
      }
    },
    async setDefaultCompany() {
      const user = JSON.parse(localStorage.getItem("user")) || {};
      let driverInfo;
      if (user.type === 2) {
        const res = await detailsDriver({ id: user.type_id });
        driverInfo = res.data;
      }
      // 承运商 || 外部司机
      if (
        user.type === 3 ||
        (user.type === 2 && driverInfo.driver_type === "1")
      ) {
        // 默认委外
        this.ruleForm.type = "1";
        // 置灰
        this.typeDisable = true;
        // 承运商默认
        this.ruleForm.company_id =
          user.type === 3 ? user.type_id + "" : driverInfo.carrier_id + "";
        this.handleChangeCompany(this.ruleForm.company_id);
      }
    },
    // 获取运单数据通过数据
    async agewaybillList(value) {
      // console.log(value.from_network_id);
      if (value.from_network_id && value.from_network_id != 0) {
        // 通过目的网点获取发货地址
        var startparam = {
          id: value.from_network_id * 1,
        };
        await organizationDetail(startparam).then((res) => {
          this.organizaList = res.data;
          //  调用获取地址详情接口
        });
        this.endareaList = await this.PagerecognitionListcity(
          this.ruleForm.take_address
        );
        this.pageaccountingrules();
      } else {
        this.organizaList = {
          address: "",
          province_id: 0,
          city_id: 0,
        };
        // await this.PagerecognitionListcity(this.ruleForm.take_address)
        this.pageaccountingrules();
      }
    },
    // 通过详细地址获取省市区id
    async PagerecognitionListcity(value) {
      let data = {
        detail_address: value,
      };
      var resdata = {};
      await recognitionListcity(data).then((res) => {
        resdata = res.data;
      });
      return resdata;
    },
    // // 计费规则接口
    pageaccountingrules(type, val) {
      // this.rule_cost_info_id = "";
      // // // 计费规则调用
      // var param = {
      //   node: "1", // 当前节点
      //   transport_type_id: this.waybillInfo.waybill_product_type + "", // 承运类型
      //   start_area_info: {
      //     address: this.organizaList.address,
      //     province_id: this.organizaList.province_id, // 省id
      //     city_id: this.organizaList.city_id, // 市id
      //   }, // 出发区域信息
      //   end_area_info: {
      //     address: this.ruleForm.take_address,
      //     province_id: this.endareaList.province_id, // 省id
      //     city_id: this.endareaList.city_id, // 市id
      //   }, // 到达区域信息
      //   customer_id: this.waybillInfo.customer_id + "", // 客户id
      //   carrier_id: this.ruleForm.company_id == undefined ? "" : this.ruleForm.company_id + "",  // 承运商id
      //   goods_list: [
      //     {
      //       name: "",
      //       packing: "",
      //       goods_no: "",
      //       packing_type: "",
      //       number: this.ruleForm['waybill_data_list'][0].number + "",
      //       volume: this.ruleForm['waybill_data_list'][0].volume + "",
      //       weight: this.ruleForm['waybill_data_list'][0].newWeight + "",
      //       price: "",
      //       thermosphere: "",
      //       package_quantity: "",
      //       declared_value: "",
      //       remark: "",
      //     }
      //   ]
      // };
      // setTimeout(async () => {
      //   let result = await accountingrules(param);
      //   let datalist = JSON.parse(JSON.stringify(result.data));
      //   this.rule_cost_info = datalist[0].rule_cost_info;
      //   if (this.rule_cost_info.length == 1 && this.ruleForm['waybill_data_list'][0].collect_money == "") {
      //     this.rule_cost_info_id = this.rule_cost_info[0].rule_id;
      //     this.rulechange(this.rule_cost_info[0].rule_id);
      //   } else if (this.rule_cost_info.length == 1) {
      //     this.rule_cost_info_id = this.rule_cost_info[0].rule_id;
      //   }
      // });
    },
    // 选中计费规则赋值
    rulechange(value) {
      var piceList = {};
      this.rule_cost_info.forEach((element) => {
        if (element.rule_id == value) {
          piceList = element;
        }
      });
      this.$set(
        this.ruleForm["waybill_data_list"][0],
        "collect_money",
        piceList.cost
      );
      this.$forceUpdate();
    },
    // 进入页面进行调用
    invoking() {
      this.agewaybillList(this.waybillInfo);
    },
    // 修改揽收地址
    async take_address_change(val) {
      // 四川省巴中市巴州区

      await this.PagerecognitionListcity(this.ruleForm.take_address);
      this.endareaList = await this.PagerecognitionListcity(
        this.ruleForm.take_address
      );
    },
    selectCarNumber(e) {
      this.ruleForm.car_no = this.carNumberData.find(
        (item) => item.id == e
      ).license_plate;
    },
    //Notification 通知事件
    NotificationObj() {
      // console.log(this.waybillInfo, "ruleFormruleForm");
      // 数据改变
      (this.noTifyData = {
        customer_id: this.waybillInfo.customer_id + "",
        product_type_id: this.waybillInfo.waybill_product_type,
        node_id: "1",
      }),
        (this.notifyType = true);
    },
  },
};
</script>
<style lang="less">
.temperature_msg {
  width: auto;
}

.info_tab {
  width: 100%;
  height: 40px;
  background: #f2f3f5;
  font-weight: bold;
  line-height: 40px;
  padding-left: 12px;
  margin-bottom: 16px;
  color: #45474c;
  display: flex;

  .info_tab_list {
    display: flex;
    margin-left: 20px;
    font-size: 13px;
    font-weight: none;
  }
}

.el-form--label-top .el-form-item__label {
  padding: 0 !important;
}

.el-table .cell .el-input.el-input--mini {
  width: auto !important;
}
</style>
<style lang="less" scoped>
.el-table__body {
  width: 100% !important;
  table-layout: fixed !important;
}
</style>
